# coding: utf-8
import time
import re
import json
import urllib
import urllib2
import traceback
import os
from StringIO import StringIO
from datetime import timedelta, datetime
from flask import Blueprint
from flask import url_for
from flask import render_template
from flask import request, g
from flask import redirect, abort
from flask import session
from leancloud import Object, Query, File, GeoPoint, LeanCloudError

from tools import logging, wrapsfuncs
from dbModels import AGMSHOP, AgmProduct, AgmFwCode, AgmQrRecord, AgmSucGetJf, AgmSeller, AgmSellCount
from dbModels import AgmSellRecord, WepaySuccess, AgmKf, AgmSellRegistLog
from dbModels import getQuerySelfCache

agmbeta_view = Blueprint('agmbeta', __name__)
agmbeta_view_en = Blueprint('agmbeta_en', __name__, url_prefix='/en')


# TAGID = '563ac7d360b2c0a27d84cfdc' #12-15 BAK
TAGID = '566f6e3460b294bccfd45c03'
DEALERCONFIGID = '56c6e1c3c4c9710057a74f58'
NEWTAG = u'2020最新产品'
QRJF = 20  #扫码获得积分值

TAGDICT = {
    u'1:43智能系列': (u'1:43智能ASR系列', '1:43 ASR Series(Smart)'),
    u'1:43数码系列': (u'1:43数码DTR系列', '1:43 DTR Series(Digital)'),
    u'1:43模拟系列': (u'1:43模拟TR系列', '1:43 TR Series(Analog)'),
    u'1:43通用配件包系列': (u'1:43通用配件包系列', '1:43 Accessory Pack'),
    u'1:64模拟系列': (u'1:64模拟MR系列', '1:64 MR Series(Analog)'),
    u'逻辑货运车SL系列': (u'逻辑货运车SL系列', 'SL Series(Analog)'),
    u'GD积木轨道系列': (u'GD积木轨道系列', 'GD Series(Blocks)')
}

TRANS_DICT = {
    u'1:43智能系列': '1:43 ASR Series',
    u'1:43数码系列': '1:43 DTR Series',
    u'1:43模拟系列': '1:43 TR Series',
    u'1:43通用配件包系列': '1:43 Accessory Pack',
    u'1:64模拟系列': '1:64 MR Series',
    u'逻辑货运车SL系列': 'SL Series(Analog)',
    u'GD积木轨道系列': 'GD Series(Blocks)',
    NEWTAG: 'New Products'
}

P_TAGS = [
    u'GD积木轨道系列',
    u'逻辑货运车SL系列',
    u'1:64模拟系列',
    u'1:43智能系列',
    #u'1:43数码系列',
    u'1:43模拟系列',
    u'1:43通用配件包系列' 
]

HDLABEL = u'新春红包'
HDDATE = '2016-2-22 21:00'
ISHDOUT = lambda: datetime.now() >= datetime.strptime(HDDATE, '%Y-%m-%d %H:%M')
HDLABEL = None
ISLOCAL = os.environ.get('VIRTUAL_ENV', '').startswith('F:')

bigtosmall = lambda x: x.replace('BigPic', 'SmallPic').replace('.jpg', 's.jpg')

def _t(*texts):
    return texts[1] if 'agmbeta_en.' in request.endpoint else texts[0]
    
def _dt(text):
    return TRANS_DICT.get(text, text) if 'agmbeta_en.' in request.endpoint else text
    
@agmbeta_view.context_processor
@agmbeta_view_en.context_processor
def innerfunc():
    return dict(_t=_t, _dt=_dt, enumerate=enumerate)
    

@agmbeta_view.route('/')
@agmbeta_view_en.route('/')
@logging.log
@logging.agmlog
def index():
    items = [
        {'title': _t(u'公司简介', 'About Us'), 'link': url_for('.about')},
        {'title': _t(u'路轨赛车的历史', 'Slot Cars History'), 'link': url_for('.history')},
        {'title': _t(u'产品推荐', 'Products')},
        {'title': _t(u'产品功能及特点介绍', 'Function&Features'), 'link': url_for('.feature')},
        {'title': _t(u'正品查询', 'Product Authentication'), 'link': url_for('.fwquery')},
        {'title': _t(u'App下载', 'App Download'), 'link': url_for('.downapp')},
        {'title': _t(u'会员分享', 'Members Forums'), 'link': url_for('.memberposts')},
        {'title': _t(u'视频专区', 'Videos'), 'link': url_for('.video')}, 
        {'title': _t(u'产品说明书', 'Instructions'), 'link': url_for('.instruction')}, 
        {'title': _t(u'联系我们', 'Contact Us'), 'link': url_for('.contact')},
        ]
    # tags = Query(Object.extend('Cache_list')).get(TAGID).get('content') #selfCache
    # tags = getQuerySelfCache(Query(Object.extend('Cache_list')), 'get', TAGID).get('content')
    tags = P_TAGS
    tagitems = [{'title': _t(NEWTAG, 'New Products in 2020'), 'link': url_for('.products')}]
    for i, item in enumerate(tags):
        tagitems.append({'title': _t(*TAGDICT.get(item, item)), 'link': url_for('.products', bid=i+1)})    
    items[2]['items'] = tagitems
    wxjs_sign()
    return render_template('agm1.0/agmbeta.html', title=_t(u'AGM 英宝玩具', 'Top-Racer'), items=items,
        timestamp=int(time.time()), enumerate=enumerate)

@agmbeta_view.route('/about')
@agmbeta_view_en.route('/about')
@logging.log
@logging.agmlog
def about():
    return render_template('agm1.0/agm_about.html')
    
@agmbeta_view.route('/trackCheck')
@agmbeta_view_en.route('/trackCheck')
@logging.log
@logging.agmlog
def trackCheck():
    is_en =  'agmbeta_en.' in request.endpoint
    return render_template('agm1.0/agm_track_check.html', is_en=is_en) 

@agmbeta_view.route('/trackCheck1')
@agmbeta_view_en.route('/trackCheck1')
@logging.log
@logging.agmlog
def trackCheck1():
    is_en =  'agmbeta_en.' in request.endpoint
    return render_template('agm1.0/agm_track_check1.html', is_en=is_en)     

@agmbeta_view.route('/ft3D')
@agmbeta_view_en.route('/ft3D')
@logging.log
@logging.agmlog
def ft3D():
    ftid = request.args.get('id')
    ft3Ds = {
        '02': ('FT-02', 'D5S4hTW7-PmCQaSTg-npFtRIDh-xhBImR9D'),
        '03': ('FT-03', 'Z46a6zwk-pwfB4mLu-T3td09K3-oOUHWUgJ'),
        '04': ('FT-04', 'vs7UCxpr-EZ7Thulg-vbtxTY9o-S5erhN3H')
    }
    if(ftid not in ft3Ds):
        ftid = '02'
    ft = ft3Ds[ftid]
    return render_template('agm1.0/agm_ft3D.html', ft=ft) 
    
@agmbeta_view.route('/history')
@agmbeta_view_en.route('/history')
@logging.log
@logging.agmlog
def history():
    wxjs_sign()
    return render_template('agm1.0/agm_history.html')

@agmbeta_view.route('/feature')
@agmbeta_view_en.route('/feature')
@logging.log
@logging.agmlog
def feature():
    return render_template('agm1.0/agm_feature.html') 

@agmbeta_view.route('/downapp')
@agmbeta_view_en.route('/downapp')
@logging.log
@logging.agmlog
def downapp():
    is_en =  'agmbeta_en.' in request.endpoint
    return render_template('agm1.0/agm_downapp.html', is_en=is_en)       
        
    
@agmbeta_view.route('/instruction')
@agmbeta_view_en.route('/instruction')
@logging.log
@logging.agmlog
def instruction():
    pid = request.args.get('pid')
    if pid:
        product = Query(AgmProduct).get(pid)
        if product.get('sm'):
            return render_template('agm1.0/agm_instruct.html', product=product)
    query = Query(AgmProduct)
    query.exists('sm')
    query.does_not_exist('hide')
    query.ascending('name')
    products = query.find()
    return render_template('/agm1.0/agm_instructs.html', items=products, bigtosmall=bigtosmall)
    
@agmbeta_view.route('/sellmap')
@agmbeta_view_en.route('/sellmap')
@logging.log
@logging.agmlog
def sellmap():
    if request.args.get('action') == 'js':
        # shops = Query(AGMSHOP).find() #selfCache
        shops = getQuerySelfCache(Query(AGMSHOP), 'find')
        items = []
        for shop in shops:
            items.append(shop.dump())
        return json.dumps(items)
    if request.args.get('action') == 'map':
        return render_template('agm1.0/map.html') 
    if request.args.get('action') == 'setting':
        return render_template('agm1.0/agm_map_setting.html')
    # shops = Query(AGMSHOP).find() #selfCache
    shops = getQuerySelfCache(Query(AGMSHOP), 'find')
    return render_template('agm1.0/agm_map.html', shops=shops, timestamp=int(time.time()))
        
@agmbeta_view.route('/contact')
@agmbeta_view_en.route('/contact')
@logging.log
@logging.agmlog
def contact():
    return render_template('agm1.0/agm_contact_beta.html')
    
@agmbeta_view.route('/fromqrcode')
@agmbeta_view_en.route('/fromqrcode')
@logging.log
@logging.agmlog
def fromqrcode():
    pname = request.args.get('pname')
    if pname:
        return u'<title>二维码校对</title><h1>您扫描的二维码型号为:%s</h1>' % pname
    return redirect(url_for('agmbeta.downapp'))   
    
@agmbeta_view.route('/fwquery0')
@agmbeta_view_en.route('/fwquery0')
@logging.log
@logging.agmlog
def fwquery0():
    return render_template('agm1.0/agm_fw.html')

@agmbeta_view.route('/fwquery')
@agmbeta_view_en.route('/fwquery')
@logging.log
@logging.agmlog
def fwquery():
    fwcode = request.args.get('qrcode')
    if fwcode and not(len(fwcode) == 16 and fwcode.isdigit()):
        fwcode = None
    if request.cookies.get('role') == 'agmsell' and not request.args.get('direct') and fwcode:
        directpage = request.cookies.get('fwcodedirect')
        if directpage == 'sellpage':
            return redirect(url_for('agmbeta.sellhome', qrcode=fwcode))
        if not directpage:
            return redirect(url_for('agmbeta.fwchoice', qrcode=fwcode))
    wxjs_sign()
    return render_template('agm1.0/agm_fw_beta.html', fwcode=fwcode)

@agmbeta_view.route('/memberjf')
@agmbeta_view_en.route('/memberjf')
@logging.log
@logging.agmlog
def memberjf():
    wechatuserid = session.get('wechatuserid')
    if wechatuserid:
        g.wechatuser = Query(Object.extend('WechatUser')).get(wechatuserid)
        openid = g.wechatuser.get('openid')
        g.items = Query(AgmSucGetJf).equal_to('openid', openid).descending('createdAt').find()
    return render_template('agm1.0/agm_jf.html', timedelta=timedelta)      
    
@agmbeta_view.route('/products')
@agmbeta_view_en.route('/products')
@logging.log
@logging.agmlog
def products():
    bigtosmall = lambda x: x.replace('BigPic', 'SmallPic').replace('.jpg', 's.jpg')
    bid = request.args.get('bid')
    if bid and bid.isdigit():
        bid = int(bid)
        items = []
        # tags = Query(Object.extend('Cache_list')).get(TAGID).get('content') # selfCache
        # tags = getQuerySelfCache(Query(Object.extend('Cache_list')), 'get', TAGID).get('content')
        tags = P_TAGS
        query = Query(AgmProduct)
        #hide products
        query.does_not_exist('hide')
        tag = tags[bid-1]
        query.equal_to('tag', tag).ascending('createdAt')
        # items = query.find()  # selfCache
        items = getQuerySelfCache(query, 'find')
    else:
        # items = Query(AgmProduct).equal_to('year', 2016).ascending('createdAt').find() # selfCache
        items = getQuerySelfCache(Query(AgmProduct).does_not_exist('hide').equal_to('year', 2020).ascending('createdAt'), 'find')
        tag = NEWTAG
    wxjs_sign()
    return render_template('agm1.0/agm_listpic_beta.html', title=tag, 
        items=items, bigtosmall=bigtosmall, timestamp=int(time.time()))
    
@agmbeta_view.route('/product')
@agmbeta_view_en.route('/product')
@logging.log
@logging.agmlog
def product():
    pid = request.args.get('pid')
    item = {}
    if pid:
        # item = Query(AgmProduct).get(pid) # selfCache
        try:
            item = getQuerySelfCache(Query(AgmProduct), 'get', pid)
        except LeanCloudError:
            pass
    if not item:
        return abort(404)
    wxjs_sign()
    return render_template('agm1.0/agm_detail_beta.html', item=item,
        timestamp=int(time.time()))
    
@agmbeta_view.route('/video')
@agmbeta_view_en.route('/video')
@logging.log
@logging.agmlog
def video():
    vid = request.args.get('vid')
    if vid:
        # item = Query(Object.extend('AgmYoukuVideo')).get(vid).dump() # selfCache
        try:
            item = getQuerySelfCache(Query(Object.extend('AgmYoukuVideo')), 'get', vid)
            item.increment('viewcount', 1).save()
            item = item.dump()
        except LeanCloudError:
            return abort(404)
        item['youkuid'] = item['link'].split('id_')[-1].split('.html')[0]
        item['title'] = item['title']
        return render_template('agm1.0/agm_video.html', item=item, timestamp=int(time.time()))
    # videos = query.find()  # selfCache
    tags = [
        [u'安装指导视频', [u'套装快速拼装视频', u'TR模拟系列 使用指导视频', u'DTR数码系列 使用指导视频', u'ASR智能系列 使用指导视频', u'MR模拟系列 使用指导视频', u'DTR/MR 系列细节处理视频', u'GD 积木系列 使用指导视频', u'商用定制 相关指导视频', u'其他指导视频']],
        [u'推广视频', [u'广告推广', u'玩名堂节目']],
        [u'其它视频',[u'玩家视频']]
    ]
    cid = request.args.get('cid')
    tid = request.args.get('tid')
    if cid and tid:
        tag = tags[int(cid)][1][int(tid)]
        query = Query(Object.extend('AgmYoukuVideo')).equal_to('tag', tag).descending('viewcount')
        # videos = getQuerySelfCache(query, 'find')
        videos = query.find()
        videos.sort(key=lambda x:x.get('rank'))
        wxjs_sign()
        return render_template('agm1.0/agm_videos2.html', 
            items=videos, tag=tag)
    
    # items = {}
    # for video in videos:
        # tag = video.get('tag1')
        # if tag not in items: items[tag] = []
        # item = video.dump()
        # item['head'] = video.get('title1')
        # item['des'] = '%s %s' % (tag, item['head'])
        # items[tag].append(item)
    # for t in items:
        # items[t].sort(key=lambda x:x.get('rank'))
    wxjs_sign()    
    return render_template('agm1.0/agm_videos1.html', 
        tags=tags)
        
@agmbeta_view.route('/postweb', methods=['POST', 'GET'])
@agmbeta_view_en.route('/postweb', methods=['POST', 'GET'])
@logging.log
@logging.agmlog
def postweb():
    if request.method == 'POST':
        wechatuserid = session.get('wechatuserid')
        if wechatuserid:
            try:
                wechatuser = Query(Object.extend('WechatUser')).get(wechatuserid)
            except:
                session.pop('wechatuserid')
                return 'NoUserSessionDeleted'
        else:
            return 'nosession'
        title = request.form.get('title')
        sharetype = request.form.get('sharetype')
        #----- sharetype check-----#
        stypes = [u'玩家经验', u'玩家解惑', u'活动相关']
        if HDLABEL: stypes.append(HDLABEL)
        if sharetype not in stypes:
            return 'sharetypeinvalid'
        #-------End check-----#
        #----  HDLABEL one post limit ---#
        if sharetype == HDLABEL:
            if ISHDOUT():
                return 'VoteEnd'
            query = Query(Object.extend('AgmMemberPost'))
            query.equal_to('wechatuser', wechatuser)
            query.equal_to('sharetype', sharetype)
            query.equal_to('status', 0)
            if query.find():
                return 'postalready'
        
        #------ End one post limit ----#
        content = request.form.get('textarea')
        imageids = request.form.get('imageids')
        imgdecs = request.form.get('imgdecs') or []
        if imgdecs: #处理过滤%u 
            imgdecs = imgdecs.replace('%u', '\\u').replace('%25u', '%u')
            imgdecs = json.loads(imgdecs)
        if imageids:
            imgfiles = []
            imgurls = []
            imageids = imageids.split(',')
            from tools.wechatAPI import getimagedata
            for imageid in imageids:
                ret = getimagedata(imageid)
                filename = re.search('filename="(.+?)"', ret.headers.get('Content-disposition')).group(1)
                imagedata = StringIO(ret.read())
                file = File(filename, imagedata)
                file.save()
                imgfiles.append(file)
                imgurls.append(file.url)
            post = Object.extend('AgmMemberPost')()
            post.set('title', title).set('content', content).set('sharetype', sharetype)
            post.set('imgfiles', imgfiles).set('imgurls', imgurls).set('imgdecs', imgdecs)
            post.set('wechatuser', wechatuser)
            post.save()                
            return 'done'
        return 'faild'

    from tools.wechatAPI import getjssign
    # sign = getjssign(request.url)
    wxjs_sign()
    g.taglabel = HDLABEL
    return render_template('agm1.0/agm_post.html', timestamp=int(time.time()),)

        
@agmbeta_view.route('/memberposts')
@agmbeta_view_en.route('/memberposts')
@logging.log
@logging.agmlog
def memberposts():
    pid = request.args.get('pid')
    if pid:
        item = Query(Object.extend('AgmMemberPost')).get(pid)
        item.increment('viewcount', 1)
        item.save()
        fixpost(item)
        wxjs_sign()
        authwx()
        g.taglabel = HDLABEL
        return render_template('agm1.0/agm_posts_id.html', 
            timestamp=int(time.time()), item=item, enumerate=enumerate, len=len)
    query = Query(Object.extend('AgmMemberPost'))
    if not os.environ.get('VIRTUAL_ENV', '').startswith('F:'):
        query.not_equal_to('status', -1)
        if session.get('wechatrole') not in ['agmadmin', 'agmsell']:
            query.equal_to('status', 0)

    # query.greater_than('updatedAt', )
    # query.descending('createdAt')  #按时间排序
    query.descending('likecount')  #按点赞数排序
    posts = query.find()
    items = {'posts': {}, 'keys': [], 'label': []}
    wechatuserdict = {}
    stypes = [u'玩家经验', u'玩家解惑', u'活动相关']
    def indextype(x):
        try:
            ret = stypes.index(x)
            return 0
        except ValueError:
            return 999
    for post in posts:
        post.created_at = post.created_at + timedelta(hours=8)
        wechatuser = post.get('wechatuser')
        if wechatuser:
            if wechatuser.id not in wechatuserdict:
                wechatuser.fetch()
                wechatuserdict[wechatuser.id] = {
                'author': wechatuser.get('nickname_emoji') or wechatuser.get('nickname')}
            post.set('author', wechatuserdict[wechatuser.id]['author'])
        # key = post.created_at.strftime('%A, %B %d, %Y') #按时间分
        key = post.get('sharetype')
        if key not in items['posts']: 
            items['keys'].append(key)
            items['posts'][key] = []
        items['keys'].sort(key=indextype)  #按以类型分
        label = post.get('sharetype')
        if label and label not in items['label']:
            items['label'].append(label)
        items['posts'][key].append(post)
    from tools.wechatAPI import getjssign
    # sign = getjssign(request.url)
    wxjs_sign()
    g.taglabel = HDLABEL
    return render_template('agm1.0/agm_posts.html', timestamp=int(time.time()),
        items=items, len=len)    


@agmbeta_view.route('/auth')
@agmbeta_view_en.route('/auth')
@logging.log
@logging.agmlog
def auth():
    code = request.args.get('code')
    if code:
        code = request.args.getlist('code')[-1]
    from tools.wechatAPI import getauth
    openid = getauth(code) if code else None
    if not openid:
        from tools.wechatAPI import getauthurl
        import logging
        logging.error('Auth1 GetOpenidFromCodeFaildRedrectToSelfUrl Code:%s' % code)
        return redirect(getauthurl(request.url))
    session['openid'] = openid
    query = Query(Object.extend('WechatUser'))
    query.equal_to('openid', openid)
    try:
        wechatuser = query.first()
        userid = wechatuser.id
        session['wechatuserid'] = userid
        if wechatuser.get('role'):
            session['wechatrole'] = wechatuser.get('role')
        else:
            session.pop('wechatrole', None)            
    except:
        import logging
        logging.error('Auth1 GetOpenidSuccessButNotInWechatUser:%s' % openid)
        try:
            from tools.wechatAPI import get_save_userinfo_api
            wechatuser = get_save_userinfo_api(openid)
            userid = wechatuser.id
            session['wechatuserid'] = userid
            if wechatuser.get('role'):
                session['wechatrole'] = wechatuser.get('role')
            else:
                session.pop('wechatrole', None)
        except:
            logging.error(traceback.format_exc())
    goto = request.args.get('goto')
    pid = request.args.get('pid')
    if goto:
        try:
            if pid:
                return redirect(url_for('.%s' % goto, pid=pid))
            return redirect(url_for('.%s' % goto))
        except:
            pass
    return redirect(url_for('.index'))

@agmbeta_view.route('/auth2')
@agmbeta_view_en.route('/auth2')
@logging.log
@logging.agmlog
def auth2():
    code = request.args.get('code')
    goto = request.args.get('goto')
    from tools.wechatAPI import getauth, getauthurl
    if request.args.get('type') == 'getinfo':
        if code and code != 'authdeny':
            ret = getauth(code, True, True)
            openid = ret.get('openid')
            session['wechatuserid'] = ret.get('wechatuserid')
        else:
            import logging
            logging.error('Auth2 Get Authdeny')
            # return 'You Deny the Info Get!'
    elif not code:
        # return '<a href="%s">%s</a>' % (getauthurl(request.url), getauthurl(request.url)) #add temp
        return redirect(getauthurl(request.url))
    else:
        openid = getauth(code)
        session['openid'] = openid
        query = Query(Object.extend('WechatUser'))
        query.equal_to('openid', openid)
        try:
            wechatuser = query.first()
            userid = wechatuser.id
            session['wechatuserid'] = userid
            if wechatuser.get('role'):
                session['wechatrole'] = wechatuser.get('role')
            else:
                session.pop('wechatrole', None)
        except:
            from urlparse import urljoin
            # re_url = getauthurl(url_for('agmbeta.auth2', type='getinfo', goto=goto))
            re_url = getauthurl(
                urljoin(request.url_root, url_for('agmbeta.auth2', type='getinfo', goto=goto)),
                True)
            # return '<a href="%s">%s</a>' % (re_url, re_url)  #add temp
            return redirect(re_url)
    if goto:
        try:
            # return '<a href="%s">%s</a>' % (url_for('agmbeta.%s' % goto), url_for('agmbeta.%s' % goto)) #add temp
            if '.' in goto:
                return redirect(url_for('%s' % goto))
            return redirect(url_for('.%s' % goto))
        except:
            pass
    return redirect(url_for('.index'))    
    
@agmbeta_view.route('/auth3')
@agmbeta_view_en.route('/auth3')
@logging.log
@logging.agmlog
def auth3():
    code = request.args.get('code')
    cache_id = request.args.get('cacheID')
    from tools.wechatAPI import getauth
    if request.args.get('type') == 'getinfo':
        if code and code != 'authdeny':
            ret = getauth(code, True, False)
            data = {'cacheid': cache_id, 'data': ret}
            nickname = ret['nickname']
            url = 'http://www.top-racer.com/socketTest/postCode.php'
            rep = urllib2.urlopen(url, json.dumps(data))
            ret = rep.read()
            if(ret=='done'):
                return render_template('agm1.0/agm_wx_suc.html', nickname=nickname)               
            return ret
        else:            
            return 'You Deny the Info Get!'
    

    return redirect(url_for('.index'))       
    
def authwx():
    code = request.args.get('code')
    if code:
        from tools.wechatAPI import getauth
        openid = getauth(code)
        if openid:
            session['openid'] = openid
            try:
                query = Query(Object.extend('WechatUser')).equal_to('openid', openid)
                wechatuser = query.first()
                session['wechatuserid'] = wechatuser.id
                if wechatuser.get('role'):
                    session['wechatrole'] = wechatuser.get('role')
                else:
                    session.pop('wechatrole', None)
            except LeanCloudError:
                import logging
                logging.error('WxAuthGetOpenidSuccessButNotInWechatUser, openid:%s' % openid)                
            except:
                import logging
                logging.error(traceback.format_exc())
        else:
            import logging
            logging.error('WxAuthGetOpenidWithCode CodeFaild:%s' % request.url)
            session['getopeniderror'] = True
    if request.headers.get('User-Agent') and 'MicroMessenger/' in request.headers.get('User-Agent'):
        if not session.get('openid') and not session.get('getopeniderror'):
            from tools.wechatAPI import getauthurl
            g.wxauthurl = getauthurl(request.url)
        
        
    
@agmbeta_view.route('/test', methods=['POST'])
def test():
    # t0 = time.time()
    # emoji = json.load(open('tools/emoji.json'))
    # for t in emoji:
        # break
    # return 'key:%r, value:%r, time:%s' % (t, emoji[t], time.time()-t0)
    import urllib
    # test = urllib.unquote(request.form.get('test'))
    # test = request.form.get('test')
    # test = test.replace('%u', '\\u').replace('%25u', '%u')
    # test = json.loads(test)
    test = request.form.get('c_content')
    return 'result:%s' % test
    
@agmbeta_view.route('/manage', methods=['POST'])
@agmbeta_view_en.route('/manage', methods=['POST'])
@logging.log
@logging.agmlog
def manage():
    action = request.args.get('action')
    if action == 'delpost':
        wechatuserid = session.get('wechatuserid')
        if not wechatuserid:
            return 'nosession'
        try:
            wechatuser = Query(Object.extend('WechatUser')).get(wechatuserid)
        except:
            session.pop('wechatuserid')
            return 'NoUserSessionDelete'
        if wechatuser.get('role') != 'agmadmin':
            return 'NoPermission'
        pid = request.form.get('pid')
        if pid:
            from tools.manage import delmemberpost
            delmemberpost(pid)
            return 'delsuccess'
        return 'delpost:%s' % pid
    if action == 'delcomment':
        wechatuserid = session.get('wechatuserid')
        # if ISLOCAL:
             # wechatuserid = '565d91e660b20de5ec7649f6'   
        if not wechatuserid:
            return 'nosession'
        try:
            wechatuser = Query(Object.extend('WechatUser')).get(wechatuserid)
        except:
            session.pop('wechatuserid')
            return 'NoUserSessionDelete'
        if wechatuser.get('role') != 'agmadmin':
            return 'NoPermission'
        pid = request.form.get('pid')
        if pid:
            from tools.manage import delcomment
            delcomment(pid)
            return 'delsuccess'
        return 'delcomment:%s' % pid        
    elif action == 'getlike':
        # return getlikewithwechatid()
        pid = request.form.get('pid')
        if not pid:
            return 'nopid'
        memberpost = Query(Object.extend('AgmMemberPost')).get(pid)
        if memberpost.get('sharetype') == HDLABEL:
            return getlikewithopenid()
        else:
            return getlikewithwechatid()


    elif action == 'fwquery':
        # return json.dumps({'msg': 'Ahaha', 'status': 1, 'valid': 1})
        code = request.args.get('code')
        if len(code) !=16 or not code.isdigit():
            return 'invalidinput'        
        fwurl = 'http://www.4006216888.com/fw_jsonp.asp?FWcode=%s' % code
        fwurl2 = 'http://agm.leanapp.cn/test?url=%s' % urllib.quote(fwurl)
        try:
            ret = json.loads(urllib2.urlopen(fwurl2, timeout=8).read().split('(', 1)[1].rsplit(')', 1)[0])[0]
        except:
            import logging
            logging.error('fwquery get faild:%s' % fwurl2)
            return json.dumps({'msg': u'系统繁忙,请稍候再试'})
        result = {'msg': ret['msg'], 'code': code}
        if u'音速风暴正版产品' in ret['msg']:
            result['valid'] = True
            fwcode = Query(AgmFwCode).equal_to('code', code).find()
            openid = session.get('openid')
            if not fwcode:
                agmfwcode = AgmFwCode(code=code, status=0)
                if openid:
                    agmfwcode.set('openid', openid)
                try:
                    ret = getproductfromfwcode(code)
                    if ret['FWCode']:
                        for k in ret:
                            if ret[k]:
                                agmfwcode.set(k, ret[k])
                except:
                    agmfwcode.set('error', traceback.format_exc())
                agmfwcode.save()
                result['status'] = 0
            else:
                fwcode = fwcode[0]
                if not fwcode.get('openid') and openid:
                    fwcode.set('openid', openid).save()
                result['status'] = fwcode.get('status')
        else: 
            result['valid'] = False            
        return json.dumps(result)
    # 以下为扫码换积分功能，暂时注释不用
    # elif action == 'fwtojf':  
        # code = request.form.get('code')
        # if len(code) !=16 or not code.isdigit():
            # return 'invalidinput'
        # fwcode = Query(AgmFwCode).equal_to('code', code).find()
        # if not fwcode:
            # return json.dumps({'status': 'notexist'})
        # fwcode = fwcode[0]
        # if fwcode.get('status') == 0:            
            # qrrecord = AgmQrRecord(jf=QRJF, addtime=time.time(), code=code)
            # from random import randrange
            # randint = randrange(1, 99990)
            # qrrecord.set('randint', randint).save()
            # from tools.wechatAPI import getqrcode
            # qrurl = getqrcode(randint).get('qrurl')
            # return json.dumps({'status': 'done', 'qrurl': qrurl})
        # else:
            # return json.dumps({'status': 'already'})
    elif action == 'postcomment':
        wechatuserid = session.get('wechatuserid') # or '5645dfba60b20fc9b9a45459'
        if wechatuserid:
            pid = request.args.get('pid')
            try:
                wechatuser = Query(Object.extend('WechatUser')).get(wechatuserid)
            except:
                session.pop('wechatuserid')
                return 'NoUserSessionDelete'
            memberpost = Query(Object.extend('AgmMemberPost')).get(pid)
            c_content = request.form.get('c_content')
            agmcomment = Object.extend('AgmMemberComment')()
            agmcomment.set('memberpost', memberpost).set('wechatuser', wechatuser)
            agmcomment.set('c_content', c_content)
            agmcomment.save()
            ret = {'errorcode': 0}
            comments = []
            for c in getcomments(memberpost):
                comments.append({
                    'author': c.get('author'),
                    'headimgurl': c.get('headimgurl') or '/static/images/getheadimg.png',
                    'c_content': c.get('c_content'),
                    'c_item_date': c.created_at.strftime('%Y-%m-%d %H:%M')
                })
            ret['comments'] = comments
            return json.dumps(ret)
        else:
            return 'nosession'
    elif action == 'mapapply':
        image = request.files.get('file')
        args = dict(
            title = request.form.get('title'),
            addr = request.form.get('address'),
            phone = request.form.get('phone'),
            lat = request.form.get('lat'),
            lng = request.form.get('lng'),
        )
        for t in args:
            if not args[t]:
                return 'no%s' % t
        agmshop = AGMSHOP(**args)
        agmshop.set('location', GeoPoint(
            latitude=float(args['lat']), longitude=float(args['lng'])))
        if image:
            if not image.content_type.startswith('image'):
                return 'notimage'
            filename = image.filename
            file = StringIO(image.stream.read())
            file = File(filename, file).save()
            agmshop.set('imgfile', file)
            agmshop.set('imgurl', file.url)
            agmshop.save()
        else:
            return 'noimage'
        return 'done'
        # return 'mapapply:%s' % request.form.get('lat')
    elif action == 'sellpostimage':
        image = request.files.get('imgfile')
        pname = request.form.get('pname')
        return 'Done with %s, %s' % (image, pname)
    elif action == 'sellregister':
        openid = session.get('openid') # or 'testopenid'
        if ISLOCAL:
            openid = 'ohCrcvq5TTqoF1eP4p2oLn6rte2k'
        if not openid:
            return 'nosesssionget'
        saveRegistLog(openid)
        # return 'sellregistersuccess'
        # if Query(AgmSeller).equal_to('openid', openid).find():
            # return 'alreadypost'
        wechatuser = Query(Object.extend('WechatUser')).equal_to('openid', openid).find()
        if not wechatuser:
            return 'nofollowyet'
        wechatuser = wechatuser[0]
        dealerconfig = Query(Object.extend('Cache_dict')).get(DEALERCONFIGID).get('content')
        dealercode = request.form.get('dealercode')
        if dealercode not in dealerconfig['dealercodes']:
            return 'nodealercode'
        else:
            dealername = dealerconfig['dealers'][dealercode]['name']

        agmseller = Query(AgmSeller).equal_to('openid', openid).find()
        if agmseller:
            agmseller = agmseller[0]
        else:
            agmseller = AgmSeller(openid=openid, accept=0)
            agmseller.set('nickname', wechatuser.get('nickname_emoji') or wechatuser.get('nickname'))
            agmseller.set('headimgurl', wechatuser.get('headimgurl'))
            agmseller.set('accept', 0)
        # 增加自动识别shopcode
        SHOPCODESID = '57e64aec5bbb50005d53f63f'
        shopcodes = Query(Object.extend('Cache_dict')).get(SHOPCODESID).get('content')
        shopcode = request.form.get('shopcode')
        if shopcode not in shopcodes:
            return 'noshopcode'
        else:
            shopname = shopcodes[shopcode]['name']
            shopaddr = shopcodes[shopcode]['addr']            
        agmseller.set('shopcode', shopcode).set('shopname', shopname).set('shopaddr', shopaddr)        
        agmseller.set('dealercode', dealercode).set('dealername', dealername)        
        keys = ['wxid', 'phone']        
        for k in keys:
            agmseller.set(k, request.form.get(k))      
        
        agmseller.save()
        
        return 'sellregistersuccess'
    elif action == 'acceptseller':
        # return 'acceptsuccess'
        openid = session.get('openid')
        if ISLOCAL:
            openid = 'ohCrcvlQMzCovAxALwzdNOs8yNf8'
        if not Query(Object.extend('WechatUser')).equal_to('openid', openid).equal_to('role', 'agmadmin').find():
            return 'sessionerror'        
        sellerid = request.args.get('sellerid')
        agmseller = Query(AgmSeller).get(sellerid)
        openid = agmseller.get('openid')
        wechatuser = Query(Object.extend('WechatUser')).equal_to('openid', openid).find()
        if not wechatuser:
            return 'openidnotfetch'
        wechatuser = wechatuser[0]
        from tools.wechatAPI import movetogroup
        if request.form.get('cancel'):
            if wechatuser.get('role') != 'agmadmin':
                wechatuser.unset('role').save()
            agmseller.set('accept', -1).save()
            movetogroup(openid, 0)
        else:
            if wechatuser.get('role') != 'agmadmin':    
                wechatuser.set('role', 'agmsell').save()
            agmseller.set('accept', 1).save()
            movetogroup(openid, 102)
        return 'acceptsuccess'
    elif action == 'selladdproduct':
        # result = {
            # 'pname': 'TR-01',
            # 'reward': 5,
            # 'ctime': '160101 5:56'        
        # }
        # return json.dumps(result)        
        fwcode = request.args.get('fwcode')
        if len(fwcode) !=16 or not fwcode.isdigit():
            return 'invalidinput'
        # openid = session.get('openid') or 'ohCrcvq5TTqoF1eP4p2oLn6rte2k'
        openid = session.get('openid') if not ISLOCAL else 'ohCrcvq5TTqoF1eP4p2oLn6rte2k'
        if not openid:
            return 'nosession'
        # if session.get('wechatrole') != 'agmsell' and False:
        if session.get('wechatrole') not in  ['agmsell', 'agmadmin'] and not ISLOCAL:        
            return 'notagmsell'
        agmseller = Query(AgmSeller).equal_to('openid', openid).find()
        if not agmseller:
            return 'noagmsellerofopenid'
        else:
            agmseller = agmseller[0]
        
        agmfwcode = Query(AgmFwCode).equal_to('code', fwcode).find()
        if not agmfwcode:
            ret = getproductfromfwcode(fwcode)

            if not ret['FWCode']:
                return 'fwcodenotfetch'
            agmfwcode = AgmFwCode(code=fwcode, status=0)
            for k in ret:
                if ret[k]:
                    agmfwcode.set(k, ret[k])
            agmfwcode.set('createdbysell', True)
        else:
            agmfwcode = agmfwcode[0]
            if not agmfwcode.get('FWCode'):
                return 'fwcodenotfetch'
            if agmfwcode.get('sellopenid'):
                return 'alreadyget'
        agmsellrecord = AgmSellRecord(
            openid=openid, 
            code=fwcode,
            shopcode=agmseller.get('shopcode'),
			shopname=agmseller.get('shopname'),
            dealercode=agmseller.get('dealercode')
        )
        keys = ['ProductCode', 'ProductName', 'ReceivingComName', 'ProductDate', 'BBarCode', 'SBarCode', 'ProductTypeName']
        for k in keys:
            if agmfwcode.get(k):
                agmsellrecord.set(k, agmfwcode.get(k))
        dealerconfig = Query(Object.extend('Cache_dict')).get(DEALERCONFIGID).get('content')        
        rewardconfig = getrewardconfig(dealerconfig, agmseller)        
        agmsellrecord.set('reward', getsellreward(agmfwcode.get('ProductName'), rewardconfig))
        agmsellrecord.set('rewardstat', 0)
        try:
            agmsellrecord.save()
            agmfwcode.set('sellopenid', openid).save()
        except LeanCloudError:
            return 'saveAleadyError'
            
        # agmsellcount....
        try:
            agmsellcount = Query(AgmSellCount).equal_to('openid', openid).first()
        except LeanCloudError:
            agmsellcount = AgmSellCount(openid=openid, dealercode=agmseller.get('dealercode'), today=0, week=0, month=0, total=0)
        agmsellcount.increment('today', 1).increment('week', 1).increment('month', 1).increment('total', 1).save()
                        
        result = {
            'pname': simplify_pname(agmsellrecord.get('ProductName')),
            'reward': agmsellrecord.get('reward'),
            'ctime': printDateTime(agmsellrecord.created_at)
        }
        return json.dumps(result)
    elif action == 'rewardseller':
        openid = session.get('openid')
        if ISLOCAL:
            openid = 'ohCrcvq5TTqoF1eP4p2oLn6rte2k'
        if not Query(Object.extend('WechatUser')).equal_to('openid', openid).equal_to('role', 'agmadmin').find():
            if session.get('role') not in ['agmadmin', 'agmredpacket']:
                return 'sessionerror'
        rewardids = request.form.get('rewardids').strip('|').split('|')
        sucids = []
        failids = []
        rewardsum = 0
        for rid in rewardids:
            try:
                sellrecord = Query(AgmSellRecord).get(rid)
                if sellrecord.get('rewardstat') == 0:
                    sellrecord.set('rewardstat', 1)
                    sellrecord.set('rewardtime', datetime.utcnow())
                    sellrecord.save()
                    rewardsum += sellrecord.get('reward')
                    sucids.append([rid, printDateTime(sellrecord.get('rewardtime'), '%Y-%m-%d %H:%M:%S')])
                else:
                    failids.append(rid)
            except LeanCloudError:
                failids.append(rid)
                
        return json.dumps({'sucids': sucids, 'failids': failids, 'rewardsum': rewardsum})
        
    elif action == 'modifydealersetting':
        openid = session.get('openid')
        if ISLOCAL:
            openid = 'ohCrcvlQMzCovAxALwzdNOs8yNf8'
        if not Query(Object.extend('WechatUser')).equal_to('openid', openid).equal_to('role', 'agmadmin').find():
            return 'sessionerror'
        data = request.form.get('dealerconfig')
        dealerconfig0 = json.loads(data)
        dealerconfig = upperdealerconfig(dealerconfig0)
        if dealerconfig is False:
            return 'inputfaild'
        Query(Object.extend('Cache_dict')).get(DEALERCONFIGID).set('content', dealerconfig).save()
            
        return 'modifysucess'
        
    elif action == 'setsellrecordstatus':
        openid = session.get('openid')
        if ISLOCAL:
            openid = 'ohCrcvq5TTqoF1eP4p2oLn6rte2k'
        if not Query(Object.extend('WechatUser')).equal_to('openid', openid).equal_to('role', 'agmadmin').find():
            if session.get('role') not in ['agmadmin', 'agmredpacket']:
                return 'sessionerror'
        rid = request.args.get('rid')
        record = Query(AgmSellRecord).get(rid)
        if request.args.get('setproblem'):
            record.set('rewardstat', -1)
        else:
            record.set('rewardstat', 0)
        record.save()
        return 'setproblemdone'   
    
    elif action == 'sellermodifyshop':
        openid = session.get('openid')
        if ISLOCAL:
            openid = 'ohCrcvlQMzCovAxALwzdNOs8yNf8'
        if not Query(Object.extend('WechatUser')).equal_to('openid', openid).equal_to('role', 'agmadmin').find():
            return 'sessionerror'        
        sellerid = request.args.get('sellerid')
        shopcode = request.args.get('shopcode')
        shopname = request.args.get('shopname')
        seller = Query(AgmSeller).get(sellerid)
        seller.set('shopname', shopname).set('shopcode', shopcode).save()
        return 'modifydone'
    
    elif action == 'refreshinfo':
        openid = session.get('openid')
        # if ISLOCAL:
            # openid = 'ohCrcvlQMzCovAxALwzdNOs8yNf8'  
        if not Query(Object.extend('WechatUser')).equal_to('openid', openid).equal_to('role', 'agmadmin').find():
            if session.get('role') not in ['agmadmin', 'agmredpacket']:
                return 'sessionerror' 
        sellerid = request.args.get('sellerid')
        seller = Query(AgmSeller).get(sellerid)
        openid = seller.get('openid')
        from tools.wechatAPI import get_save_userinfo_api
        ret = get_save_userinfo_api(openid)
        seller.set('headimgurl', ret.get('headimgurl'))
        seller.set('nickname', ret.get('nickname_emoji') or ret.get('nickname'))
        seller.save()
        return 'refreshdone'
    
    return 'manage'
    
def saveRegistLog(openid):
    # for t in request.form:
        # print t
    log = AgmSellRegistLog(openid=openid)
    for t in request.form:
        if request.form.get(t):
            log.set(t, request.form.get(t))
    log.save()
    
def upperdealerconfig(dealerconfig0):
    dealerconfig = {}
    for k0 in dealerconfig0:
        if k0 == 'defaultrule':
            dealerconfig[k0] = {}
            for k1 in dealerconfig0[k0]:
                try:
                    dealerconfig[k0][k1.upper()] = int(dealerconfig0[k0][k1])
                except ValueError:
                    return False
        elif k0 == 'defaultextrule':
            dealerconfig[k0] = {}
            for k1 in dealerconfig0[k0]:
                try:
                    dealerconfig[k0][int(k1)] = float(dealerconfig0[k0][k1])
                except ValueError:
                    return False            
        elif k0 == 'dealers':
            dealerconfig[k0] = {}
            for k1 in dealerconfig0[k0]:
                dealerconfig[k0][k1] = {}
                for k2 in dealerconfig0[k0][k1]:
                    if k2 == 'rule':
                        dealerconfig[k0][k1][k2] = {}
                        for k3 in dealerconfig0[k0][k1][k2]:
                            try:
                                dealerconfig[k0][k1][k2][k3.upper()] = int(dealerconfig0[k0][k1][k2][k3])
                            except ValueError:
                                return False
                    elif k2 == 'extrule':
                        dealerconfig[k0][k1][k2] = {}
                        for k3 in dealerconfig0[k0][k1][k2]:
                            try:
                                dealerconfig[k0][k1][k2][int(k3)] = float(dealerconfig0[k0][k1][k2][k3])
                            except ValueError:
                                return False                        
                    else:
                        dealerconfig[k0][k1][k2] = dealerconfig0[k0][k1][k2]
        else:
            dealerconfig[k0] = dealerconfig0[k0]
    return dealerconfig

def getrewardconfig(dealerconfig, agmseller):
    rewardconfig = dealerconfig['defaultrule']
    dealercode = agmseller.get('dealercode')
    if dealercode in dealerconfig['dealers']:
        rewardconfig.update(dealerconfig['dealers'][dealercode]['rule'])
    return rewardconfig
    
def getextrewardconfig(dealerconfig, agmseller):
    rewardconfig = dealerconfig['defaultextrule']
    dealercode = agmseller.get('dealercode')
    if dealercode in dealerconfig['dealers']:
        rewardconfig.update(dealerconfig['dealers'][dealercode]['extrule'])
    return rewardconfig

def getextreward(num, rewardconfig):
    c = 0
    for k in sorted(rewardconfig, key=lambda x:int(x)):
        if num >= int(k):
            c = rewardconfig[k]
    return num*c
    
def getlikewithwechatid():
    wechatuserid = session.get('wechatuserid')
    if not wechatuserid:
        return 'nosession'
    pid = request.form.get('pid')
    AgmGetlikeRecord = Object.extend('AgmGetlikeRecord')
    query = Query(AgmGetlikeRecord)
    query.equal_to('wechatuserid', wechatuserid).equal_to('memberpostid', pid)
    if not query.find():
        AgmGetlikeRecord(wechatuserid=wechatuserid, memberpostid=pid).save()
        memberpost = Query(Object.extend('AgmMemberPost')).get(pid)
        memberpost.increment('likecount', 1)
        memberpost.save()
        return 'Done'
    else:
        return 'AlreadyLike'

def getlikewithopenid(datelimit=True):
    if ISHDOUT():
        return 'VoteEnd'
    openid = session.get('openid')
    if not openid:
        return 'nosessionOpenid'
    pid = request.form.get('pid')
    AgmGetlikeRecord = Object.extend('AgmGetlikeRecord')
    query = Query(AgmGetlikeRecord)
    query.equal_to('openid', openid).equal_to('memberpostid', pid)
    if datelimit:
        query.greater_than('createdAt', 
            datetime.now().replace(hour=0, minute=0, second=0, microsecond=0))
    if not query.find():
        AgmGetlikeRecord(openid=openid, memberpostid=pid).save()
        memberpost = Query(Object.extend('AgmMemberPost')).get(pid)
        memberpost.increment('likecount', 1).save()
        return 'Done'
    else:
        return 'AlreadyLikeVote'
    
def getsellreward(productname, rewards):
    # rewards = {
        # 'TR-01':  5,
        # 'TR-06':  10,
    # }
    pname = simplify_pname(productname)
    return int(rewards.get(pname, 0))

def simplify_pname(pname):
    pname = re.search('[A-Za-z]+-[Cc\d]+', pname)
    if pname:
        return pname.group().upper()
    print 'FaildGetReProductNameMatch:%r' % pname
    
def fixpost(item):
    item.created_at = item.created_at + timedelta(hours=8)
    wechatuser = item.get('wechatuser')
    wechatdict = {}
    if wechatuser:
        item.set('author', 
            datafetch('nickname_emoji', wechatuser, wechatdict) or
            datafetch('nickname', wechatuser, wechatdict))
        item.set('headimgurl', datafetch('headimgurl', wechatuser, wechatdict))
    comments = getcomments(item, wechatdict)
    item.set('comments', comments)

def getcomments(memberpost, wechatdict={}):
    c_query = Query(Object.extend('AgmMemberComment'))
    c_query.equal_to('memberpost', memberpost)
    c_query.ascending('createdAt')
    c_query.not_equal_to('status', -1)
    comments = c_query.find()
    for comment in comments:
        wechatuser = comment.get('wechatuser')
        comment.created_at = comment.created_at + timedelta(hours=8)
        comment.set('author',
            datafetch('nickname_emoji', wechatuser, wechatdict) or
            datafetch('nickname', wechatuser, wechatdict))
        comment.set('headimgurl', datafetch('headimgurl', wechatuser, wechatdict))
    return comments
    
def datafetch(attr, item, m_dict):
    if item.id not in m_dict:
        item.fetch()
        m_dict[item.id] = item.dump()
    return m_dict[item.id].get(attr)

def getshopstowechat(xml):
    lat = xml.find('Location_X').text
    lng = xml.find('Location_Y').text
    p = GeoPoint(float(lat), float(lng))
    shops = Query(AGMSHOP).near('location', p).limit(3).find()
    items = [{
        'title':u'音速风暴销售商店地图', 
        'description': u'音速风暴销售商店地图',
        'picurl': 'http://m.top-racer.com/static/images/tu1.jpg',
        'url': 'http://m.top-racer.com/sellmap'
    }]
    for shop in shops:
        shop_l = shop.get('location')
        item = {
            'title': u'%s:距离约%.2f公里' % (shop.get('title'), p.kilometers_to(shop_l)),
            'description': u'音速风暴销售商店:%s' % shop.get('title'),
            'picurl': shop.get('imgurl'),
            'url': 'http://m.top-racer.com/sellmap?sid=%s' % shop.id
        }
        items.append(item)
    return items
    
def wxjs_sign():
    if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
        return
    if not request.headers.get('User-Agent') or 'MicroMessenger/' not in request.headers.get('User-Agent'):
        return
    # print 'Getting getjssign.....'
    from tools.wechatAPI import getjssign
    g.sign = getjssign(request.url) 
    
    
@agmbeta_view.route('/sellpost')
@agmbeta_view_en.route('/sellpost')
@logging.log
def sellpost():
    return render_template('agm1.0/seller/agm_sell_post.html')
    
@agmbeta_view.route('/sellregister')
@agmbeta_view_en.route('/sellregister')
@logging.log
@logging.agmlog
def sellregister():
    openid = session.get('openid')
    if ISLOCAL:
        # openid = 'ohCrcvlQMzCovAxALwzdNOs8yNf8'
        openid = 'ohCrcvq5TTqoF1eP4p2oLn6rte2k'
    seller = {}
    if not openid:
        ifseller = -1
    else:
        agmseller = Query(AgmSeller).equal_to('openid', openid).find()
        if agmseller:
            if agmseller[0].get('accept') == 1:
                return redirect(url_for('agmbeta.sellhome'))
            seller = agmseller[0]    
            ifseller = 1
        else:
            ifseller = 0
    if ISLOCAL:
        ifseller = 0

    return render_template('agm1.0/seller/agm_sell_register.html', ifseller=ifseller, seller=seller)  
    
@agmbeta_view.route('/sellerlist')
@agmbeta_view_en.route('/sellerlist')
@logging.log
@logging.agmlog
# @wrapsfuncs.wxauth_permission('agmadmin')
@wrapsfuncs.wxauth_permission_login(['agmadmin', 'agmredpacket'])
def sellerlist():
    if not checkpermission() and False:
        return render_template('agm1.0/agm_wx_deny.html')
    else:
        sellers = Query(AgmSeller).descending('createdAt').find()
        sellers0 = []
        sellers1 = []
        sellers2 = []
        for seller in sellers:
            if seller.get('accept') == 0:
                sellers0.append(seller)                
            else:
                seller.r_count = Query(AgmSellRecord).equal_to('openid', seller.get('openid')).equal_to('rewardstat', 0).count()
                if seller.get('accept') == 1:
                    sellers1.append(seller)
                else:
                    sellers2.append(seller)
		sellers1.sort(key=lambda x:x.r_count, reverse=True)
        return render_template('agm1.0/seller/agm_seller_list.html', sellers0=sellers0, sellers1=sellers1, sellers2=sellers2)


@agmbeta_view.route('/sellerinfo')
@agmbeta_view_en.route('/sellerinfo')
@logging.log
@logging.agmlog
# @wrapsfuncs.wxauth_permission('agmadmin')
@wrapsfuncs.wxauth_permission_login(['agmadmin', 'agmredpacket'])
def sellerinfo():
    uid = request.args.get('uid')
    seller = Query(AgmSeller).get(uid)
    keys = ['shopcode', 'shopname', 'shopaddr', 'wxid', 'phone']
    items = [
        (u'经销代码', 'dealercode'), 
        (u'经销商', 'dealername'),
        (u'商场代码', 'shopcode'), 
        (u'商场店名', 'shopname'), 
        (u'商场地址', 'shopaddr'),
        (u'微信ID', 'wxid'),
        (u'联系电话', 'phone')
    ]
    return render_template('agm1.0/seller/agm_seller_info.html', seller=seller, items=items)

@agmbeta_view.route('/sellhome')
@agmbeta_view_en.route('/sellhome')
@logging.log
@logging.agmlog
@wrapsfuncs.wxauth_permission(['agmsell', 'agmadmin'])
def sellhome():
    # authwx()
    openid = session.get('openid')
    if ISLOCAL:
        openid = 'ohCrcvq5TTqoF1eP4p2oLn6rte2k'
    records = Query(AgmSellRecord).equal_to('openid', openid).descending('createdAt').find()
    totalreward = 0
    alreadyreward = 0
    for r in records:
        if r.get('rewardstat') == 0:
            totalreward += r.get('reward')
        elif r.get('rewardstat') == 1:
            alreadyreward += r.get('reward')
    wxjs_sign()
    return render_template('agm1.0/seller/agm_sell_home.html', 
        records=records, spname=simplify_pname, pDT=printDateTime, totalreward=totalreward, alreadyreward=alreadyreward)

def printDateTime(t, format='%y%m%d %H:%M', fix=True, isfromTimestamp=False):
    if isfromTimestamp:
        t = datetime.fromtimestamp(t)
    if fix:
        t += timedelta(hours=8)
    return t.strftime(format)
    
@agmbeta_view.route('/selleraward')
@agmbeta_view_en.route('/selleraward')
@logging.log
@logging.agmlog
@wrapsfuncs.wxauth_permission_login(['agmadmin', 'agmredpacket'])
def selleraward():
    uid = request.args.get('uid')
    if not uid:
        abort(404)
    agmseller = Query(AgmSeller).get(uid)
    openid = agmseller.get('openid')
    records = Query(AgmSellRecord).equal_to('openid', openid).descending('createdAt').find()
    rewarded = []
    reward_wait = []
    total = 0
    daysitems = {}
    for r in records:
        if r.get('rewardstat') == 0:
            reward_wait.append(r)
            total += r.get('reward')
        elif r.get('rewardstat') == -1:
            reward_wait.append(r)
        else:
            rewarded.append(r)
        day = (r.created_at + timedelta(hours=8)).date()
        day = day - timedelta(days=day.weekday())  #以周计算
        if day not in daysitems:
            daysitems[day] = [r]
        else:
            daysitems[day].append(r)
    dealerconfig = Query(Object.extend('Cache_dict')).get(DEALERCONFIGID).get('content')        
    extrewardconfig = getextrewardconfig(dealerconfig, agmseller)
    extreward = lambda x:getextreward(x, extrewardconfig)
    return render_template('agm1.0/seller/agm_seller_awards.html',
        rewarded=rewarded, reward_wait=reward_wait, total=total, seller=agmseller,
        spname=simplify_pname, pDT=printDateTime,daysitems=daysitems, sorted=sorted, extreward=extreward, timedelta=timedelta)


        
@agmbeta_view.route('/wxdeny')
@agmbeta_view_en.route('/wxdeny')
@logging.log
def wxdeny():
    return render_template('agm1.0/agm_wx_deny.html')     


@agmbeta_view.route('/getJsSign')
def getJsSign():
    url = request.args.get('url')
    if url:
        from tools.wechatAPI import getjssign
        sign = getjssign(url)
        return json.dumps(sign)
    return 'NoUrl'    
    

@agmbeta_view.route('/dealersetting')
@agmbeta_view_en.route('/dealersetting')
@logging.log
@logging.agmlog
@wrapsfuncs.wxauth_permission('agmadmin')
def dealersetting():
    # dealerconfig = {
        # 'defaultrule': {'TR-01': 5, 'TR-06': 10},
        # 'dealers': {
            # 'testdealercode': {'name': u'测试经销商', 'rule': {'TR-06': 5}}            
        # }, 
        # 'dealercodes': ['testdealercode'],
    # }

    dealerconfig = Query(Object.extend('Cache_dict')).get(DEALERCONFIGID).get('content')
    
    return render_template('agm1.0/seller/agm_dealer_setting.html',
        dealerconfig = dealerconfig, sorted=sorted
    )      
    
@agmbeta_view.route('/sellerrank')
@agmbeta_view_en.route('/sellerrank')
@logging.log
@logging.agmlog
@wrapsfuncs.wxauth_permission_login(['agmadmin', 'agmredpacket'])
# @wrapsfuncs.wxauth_permission('agmadmin')
def sellerrank():
    rankdata = {'dealercode': {
            'name': u'测试经销商',
            'sellers': {
                '123456': {
                    'record': [['2014-01-02 13:59', 'TR-01'], ['2014-01-01 11:00', 'TR-02']],
                    'nickname': 'imfun',
                    'imgurl': '/static/images/getheadimg.png',
                    'wxid': 'testwxid1',
                    'today': 10,
                    'yesterday': 5,
                    'week': 100,
                    'lastweek': 88,
                    'month': 300,
                    'lastmonth': 250,
                },
                '123457': {
                    'record': [['2015-01-08 01:20', 'TR-03'], ['2015-01-07 14:30', 'TR-04']],
                    'nickname': 'imfun2',
                    'imgurl': '/static/images/getheadimg.png',
                    'wxid': 'testwxid2',                       
                    'today': 5,
                    'yesterday': 4,
                    'week': 200,
                    'lastweek': 99,
                    'month': 280,  
                    'lastmonth': 300,
                }
            },
            'sellshops': {
                'testshopcode1': {
                    'record': [['140102-13:59', 'imfun1', 'TR-01'], ['140101-11:00', 'imfun2', 'TR-02']],
                    'shopname': 'shopname1',
                    'today': 10,
                    'yesterday': 5,
                    'week': 100,
                    'lastweek': 88,
                    'month': 300,
                    'lastmonth': 250,
                },
                'testshopcode2': {
                    'record': [['150108-01:20', 'imfun3', 'TR-03'], ['150107-14:30', 'imfun4', 'TR-04']],
                    'shopname': 'shopname2',
                    'today': 5,
                    'yesterday': 4,
                    'week': 200,
                    'lastweek': 99,
                    'month': 280,  
                    'lastmonth': 300,                    
                }
            }
        },                
    }
    dealerconfig = {'dealercodes': ['dealercode'], 'dealers': {'dealercode': {'name': u'测试经销商'}}}
    dealerconfig = Query(Object.extend('Cache_dict')).get(DEALERCONFIGID).get('content') 
    sellrecords = Query(AgmSellRecord).descending('createdAt').find()
    rankdata = getrankdata(dealerconfig, sellrecords)
    
    return render_template('agm1.0/seller/agm_seller_rank.html',
        rankdata = json.dumps(rankdata), dealerconfig=dealerconfig 
    )

@agmbeta_view.route('/sellernav')
@agmbeta_view_en.route('/sellernav')
@logging.log
@logging.agmlog
@wrapsfuncs.wxauth_permission('agmadmin')
def sellernav():
    return render_template('agm1.0/seller/agm_seller_nav.html')       
    
    
def getrankdata(dealerconfig, sellrecords):
    rankdata = {}
    sellerscache = {}
    today = datetime.now().date()
    Monday = today - timedelta(days=today.weekday())
    monthfirst = today.replace(day=1)
    lastmonthfirst = (monthfirst - timedelta(days=1)).replace(day=1)

    for r in sellrecords:
        openid = r.get('openid')
        if openid not in sellerscache:
            seller = Query(AgmSeller).equal_to('openid', openid).first()
            sellerscache[openid] = seller
        else:
            seller = sellerscache[openid]
        # dealercode = seller.get('dealercode')
        dealercode = r.get('dealercode')
        if  dealercode not in rankdata:
            rankdata[dealercode] = {'name': seller.get('dealername'), 'sellers':{}, 'sellshops': {}}
        if seller.id not in rankdata[dealercode]['sellers']:
            rankdata[dealercode]['sellers'][seller.id] = {
                'record': [],
                'nickname': seller.get('nickname'),
                'imgurl': seller.get('headimgurl') or '/static/images/getheadimg.png',
                'wxid': seller.get('wxid'),
                'today': 0,
                'yesterday': 0,
                'week': 0,
                'lastweek': 0,
                'month': 0,
                'lastmonth': 0,
            }
        shopcode = r.get('shopcode') or 'nocode'
        shopcode = shopcode.strip().lower()
        if shopcode not in rankdata[dealercode]['sellshops']:
            rankdata[dealercode]['sellshops'][shopcode] = {
                'record': [],
                'shopname': r.get('shopname') or u'无门店名',
                'today': 0,
                'yesterday': 0,
                'week': 0,
                'lastweek': 0,
                'month': 0,
                'lastmonth': 0,                
            }
        rankdata[dealercode]['sellers'][seller.id]['record'].append([
            printDateTime(r.created_at, '%Y-%m-%d %H:%M'),
            simplify_pname(r.get('ProductName'))
        ])
        rankdata[dealercode]['sellshops'][shopcode]['record'].append([
            printDateTime(r.created_at, '%y%m%d-%H:%M'),
            seller.get('nickname'),
            simplify_pname(r.get('ProductName'))
        ])        
        #统计
        r_cdate = (r.created_at + timedelta(hours=8)).date()
        if r_cdate == today:
            rankdata[dealercode]['sellers'][seller.id]['today'] += 1
            rankdata[dealercode]['sellshops'][shopcode]['today'] += 1
        if r_cdate == today - timedelta(days=1):
            rankdata[dealercode]['sellers'][seller.id]['yesterday'] += 1
            rankdata[dealercode]['sellshops'][shopcode]['yesterday'] += 1
        if r_cdate >= Monday:
            rankdata[dealercode]['sellers'][seller.id]['week'] += 1
            rankdata[dealercode]['sellshops'][shopcode]['week'] += 1
        if Monday-timedelta(days=7) <= r_cdate < Monday:
            rankdata[dealercode]['sellers'][seller.id]['lastweek'] += 1
            rankdata[dealercode]['sellshops'][shopcode]['lastweek'] += 1
        if r_cdate >= monthfirst:
            rankdata[dealercode]['sellers'][seller.id]['month'] += 1
            rankdata[dealercode]['sellshops'][shopcode]['month'] += 1
        if lastmonthfirst <= r_cdate < monthfirst:
            rankdata[dealercode]['sellers'][seller.id]['lastmonth'] += 1
            rankdata[dealercode]['sellshops'][shopcode]['lastmonth'] += 1
            
    return rankdata
            
@agmbeta_view.route('/sellcount')
@agmbeta_view_en.route('/sellcount')
@logging.log
@logging.agmlog
@wrapsfuncs.wxauth_permission(['agmsell', 'agmadmin'])
def sellcount():
    openid = session.get('openid')
    if ISLOCAL:
        openid = 'ohCrcvq5TTqoF1eP4p2oLn6rte2k'
    try:
        seller = Query(AgmSeller).equal_to('openid', openid).first()
    except LeanCloudError:
        return abort(404)
    sellcounts = Query(AgmSellCount).equal_to('dealercode', seller.get('dealercode')).find()
    sellcount = {}
    for count in sellcounts:
        if count.get('openid') == openid:
            sellcount = count
    getrank = lambda x:getmyrank(sellcount, sellcounts, x)
       
    return render_template('agm1.0/seller/agm_sell_count.html', sellcount=sellcount, getrank=getrank, time=time)         

def getmyrank(sellcount, sellcounts, attr):
    sortedcounts = sorted(sellcounts, key=lambda x:x.get(attr), reverse=True)
    return sortedcounts.index(sellcount)+1
    
    
@agmbeta_view.route('/fwchoice')
@agmbeta_view_en.route('/fwchoice')
@logging.log
def fwchoice():
    return render_template('agm1.0/seller/agm_fwchoice.html')     

def checkpermission(role='agmadmin'):
    openid = session.get('openid')
    if openid:
        query = Query(Object.extend('WechatUser')).equal_to('openid', openid)
        wechatuser = query.find()
        if wechatuser:
            return wechatuser[0].get('role') == role
            
@agmbeta_view.route('/sellact', methods=['POST', 'GET'])
@logging.log
@logging.agmlog
@wrapsfuncs.wxauth_permission(['agmadmin', 'agmsell'])
def sellact():
    records = []
    openid = session.get('openid')
    if ISLOCAL:
        # openid = 'ohCrcvkr6Ib2k0K9_PgcVZAKPNxo'
        openid = 'ohCrcvq5TTqoF1eP4p2oLn6rte2k'
    if request.method == 'POST':
        from tools.wechatpayAPI import orderquery, savelog
        tid = request.args.get('tid')
        idtype = request.args.get('idtype')
        if not tid:
            return 'argserror'
        if idtype == '2':
            try:
                Query(WepaySuccess).equal_to('out_trade_no', tid).first()
                return 'success'
            except LeanCloudError:
                ret = orderquery(out_trade_no=tid)
        else:
            try:
                Query(WepaySuccess).equal_to('transaction_id', tid).first()
                return 'success'
            except LeanCloudError:
                ret = orderquery(tid)
        from wechatpay import etree, xmltojson
        xml = etree.XML(ret)
        data = xmltojson(xml)
        if data.get('result_code') == 'SUCCESS':
            orders = Query(Object.extend('WepayCreateorder')).equal_to('out_trade_no', data['out_trade_no']).find()
            if orders:
                data['product_id'] = orders[0].get('product_id')
            savelog(data, 'WepaySuccess')
            return 'success_add'
        else:
            data['tid'] = tid
            data['idtype'] = idtype
            savelog(data, 'WepayError')
            return data.get('err_code_des')
    query = Query(WepaySuccess)
    if session.get('wechatrole') != 'agmadmin':
        query.equal_to('attach', openid)
    from wechatpay import WEPAYORDERID, Cache_dict
    orderdict = Query(Cache_dict).get(WEPAYORDERID).get('content')
    total_done = 0
    total_wait = 0
    for t in query.descending('time_end').find():
        if not t.get('reward'): # t.get('reward') is None:
            reward = orderdict.get(t.get('product_id'), 0) and orderdict[t.get('product_id')]['reward']/100.0
        else:
            reward = t.get('reward')/100.0
        records.append({
            'time_end': datetime.strptime(t.get('time_end'), '%Y%m%d%H%M%S'),
            'total_fee': int(t.get('total_fee'))*0.01,
            'tid': t.get('transaction_id'),
            'oid': t.get('out_trade_no'),
            'product_id': t.get('product_id'),
            'rewardstat': t.get('rewardstat'),
            'reward': reward,
            'r_time': t.get('rewardtime')
        })
        if t.get('rewardstat') == 1:
            total_done += reward
        else:
            total_wait += reward
    
    return render_template('agm1.0/seller/agm_sell_act.html', records=records, total_done=total_done, total_wait=total_wait, pDT=printDateTime)            
    
def getproductfromfwcode(fwcode):
    url = 'http://120.25.102.209:8100/ApiOut/GetProductByCode?companynum=2&barcode=%s&sysKeyBase=151202102632665nmld' % fwcode
    fwurl = 'http://agm.leanapp.cn/test?url=%s' % urllib.quote(url)
    try:
        ret = json.load(urllib2.urlopen(fwurl))
    except:
        import logging
        logging.error('%s GetFaild' % fwurl)
        ret = json.load(urllib2.urlopen(url))
    return ret
    
@agmbeta_view.route('/kflist', methods=['POST', 'GET'])
@logging.log
@logging.agmlog
@wrapsfuncs.wxauth_permission('agmadmin')
def kflist():
    if request.method == 'POST':
        kfid = request.args.get('kfid')
        check = request.args.get('check')
        kf = Query(AgmKf).get(kfid)
        wechatuser = Query(Object.extend('WechatUser')).equal_to('openid', kf.get('openid')).first()
        if kf.get('headimgurl') != wechatuser.get('headimgurl'):
            kf.set('headimgurl', wechatuser.get('headimgurl'))
        if check == 'true':
            kf.set('accept', 1).save()
            if not wechatuser.get('role'):
                wechatuser.set('role', 'agmkf').save()
        else:
            kf.set('accept', 0).save()
            if wechatuser.get('role') == 'agmkf':
                wechatuser.unset('role').save()        
        return 'success'
    kfs = Query(AgmKf).find()
    return render_template('agm1.0/kf/agm_kf_list.html', kfs=kfs)  

from agmother import kf_close
